<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
  <el-select v-model="form.userType" placeholder="请选择用户类型">
    <el-option
      v-for="item in userTypeOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="出生日期" prop="birth">
        <el-date-picker clearable
          v-model="queryParams.birth"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="电子邮件" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入电子邮件"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['users:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['users:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['users:users:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['users:users:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="用户头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
  <template slot-scope="scope">
    {{ genderMap[scope.row.gender] }}
  </template>
</el-table-column>
      <el-table-column label="出生日期" align="center" prop="birth" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birth, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电子邮件" align="center" prop="email" />
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="status">
  <template slot-scope="scope">
    <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
  </template>
</el-table-column>
<el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
  <template slot-scope="scope" v-if="scope.row.userId !== 1">
    <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)" v-hasPermi="['system:user:view']">查看</el-button>
    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
      <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
      <el-dropdown-menu slot="dropdown">
        <!-- 确保用户有重置密码权限 -->
<el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
<!-- 确保用户有拉入黑名单权限 -->
<el-dropdown-item command="addToBlacklist" icon="el-icon-warning" v-hasPermi="['system:user:blacklist']">拉入黑名单</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </template>
</el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  <!-- 添加或修改app用户对话框 -->
<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
  <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
    <el-row :gutter="20">
      <el-col>
        <el-form-item label="用户头像" prop="avatar">
          <image-upload v-model="form.avatar" style="width: 100%;"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" style="width: 100%;" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="密码" prop="passwordHash">
          <el-input v-model="form.passwordHash" placeholder="请输入密码哈希" style="width: 100%;" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%;">
            <el-option label="女" value="0"></el-option>
            <el-option label="男" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker clearable
            v-model="form.birth"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出生日期"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电子邮件" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮件" style="width: 100%;" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" style="width: 100%;" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态">
          <el-radio-group v-model="form.status" style="width: 100%;">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">封停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="cancel">取 消</el-button>
  </div>
</el-dialog>

<!-- 查看 -->
<el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
  <el-descriptions class="margin-top" :column="3" border>
    <!-- Top Section -->
    <el-descriptions-item label="用户头像">
      <image-preview :src="form.avatar" :width="200" :height="200"/>
    </el-descriptions-item>
    <el-descriptions-item label="用户名">{{ form.username }}</el-descriptions-item>
    <el-descriptions-item label="性别">{{ genderMap[form.gender] }}</el-descriptions-item>
    <el-descriptions-item label="出生日期">{{ parseTime(form.birth, '{y}-{m}-{d}') }}</el-descriptions-item>
    <el-descriptions-item label="电子邮件">{{ form.email }}</el-descriptions-item>
    <el-descriptions-item label="电话号码">{{ form.phone }}</el-descriptions-item>
    <el-descriptions-item label="状态">
      <el-tag :type="form.status === 0 ? 'success' : 'danger'">
        {{ form.status === 0 ? '启用' : '封停' }}
      </el-tag>
    </el-descriptions-item>
  </el-descriptions>
  <div slot="footer" class="dialog-footer">
    <el-button @click="viewClose">关 闭</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import { listUsers, getUsers, delUsers, addUsers, updateUsers, updateUserStatus ,resetUserPwd,addBlacklist} from "@/api/siyun/appusers/appusers";

export default {
  name: "Users",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // app用户表格数据
      usersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        passwordHash: null,
        salt: null,
        avatar: null,
        gender: null,
        birth: null,
        email: null,
        phone: null,
        status: null,
        deleted: null,
        deleteId: null
      },
      viewOpen: false,

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        passwordHash: [
          { required: true, message: "密码哈希不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        rawPassword: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" }
  ],
      },
      genderMap: {
      '0': '女',
      '1': '男'
    },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleCommand(command, row) {
    if (command === 'handleResetPwd') {
      this.handleResetPwd(row);
    } else if (command === 'addToBlacklist') {
      this.addToBlacklist(row);
    }
  },
  addToBlacklist(row) {
  this.$modal.confirm('确认要将用户"' + row.username + '"拉入黑名单吗？').then(() => {
    // 弹出一个输入框让用户填写拉入原因
    this.$prompt('请输入拉入黑名单的原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '原因不能为空'
    }).then(({ value }) => {
      const syAppBlacklist = { 
        userId: row.id, // 使用 userId 而不是 username
        reason: value,  // 将用户输入的原因添加到对象中
        status: 1       // 添加状态字段，默认值为1
      };
      addBlacklist(syAppBlacklist).then(response => {
        this.$modal.msgSuccess("拉入黑名单成功");
        this.getList(); // 刷新用户列表
      }).catch(error => {
        console.error("拉入黑名单失败:", error);
        this.$modal.msgError("拉入黑名单失败");
      });
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '取消输入'
      });       
    });
  }).catch(() => {});
},

    viewClose() {
  this.viewOpen = false;
},
    handleView(row) {
  this.reset();
  const id = row.id || this.ids;
  getUsers(id).then(response => {
    this.form = response.data;
    this.viewOpen = true;
    this.title = "查看app用户";
  });
},
    /** 查询app用户列表 */
    getList() {
      this.loading = true;
      listUsers(this.queryParams).then(response => {
        this.usersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        username: null,
        passwordHash: null,
        salt: null,
        avatar: null,
        gender: null,
        birth: null,
        email: null,
        phone: null,
        userType: null,
        status: null,
        deleted: null,
        deleteId: null
      };
      this.resetForm("form");
    },
 // 用户状态修改
handleStatusChange(row) {
  let text = row.status === 0 ? "启用" : "封停";
  this.$modal.confirm('确认要"' + text + '"用户吗？').then(() => {
    return updateUserStatus(row.id, row.status);
  }).then(() => {
    this.$modal.msgSuccess(text + "成功");
  }).catch(() => {
    row.status = row.status === 0 ? 1 : 0; // 恢复原始状态
  });
},
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加app用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUsers(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改app用户";
      });
    },
    handleResetPwd(row) {
  this.$prompt('请输入"' + row.username + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/, // 确保密码长度在5到20个字符之间
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字符：< > \" ' \\\ |"
      }
      return true;
    },
  }).then(({ value }) => {
    if (value) {
      resetUserPwd(row.id, value).then(response => {
        this.$modal.msgSuccess("修改成功，新密码是：" + value);
      }).catch(error => {
        console.error("重置密码失败:", error);
        this.$modal.msgError("修改失败，请重试");
      });
    } else {
      console.warn("用户未输入密码或输入无效");
      this.$modal.msgWarning("请输入有效的密码");
    }
  }).catch(() => {
    console.log("用户取消了操作");
  });
},
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUsers(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsers(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除app用户编号为"' + ids + '"的数据项？').then(function() {
        return delUsers(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('users/users/export', {
        ...this.queryParams
      }, `users_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
